var wxOauth_url="https://wx.whyimingkeji.com/zcivcase/index.php?sjdhdh-wxoauth";//微信授权
var mySwiper,mySwiper2
// var _mid;
// _mid = getQueryVariable("mid");
var timer_num = 300; // 设置倒计时的秒数
var timer_num_all = 300; //倒计时总秒数
var is_time = false; //判断是否提交过
var jifen = 0 ; //答题分数 记住现在的分数
var curNum = 1; //记住当前的页面 第几题
var is_token = ""; //用户token
var return_obj = {}; //返回当前页面的数据对象
var ques_arr = [] //答题数组 
var jifen_all = 0;
$(document).ready(function()
{
	console.log("app")
	get_timu()
	console.log(jifen,"jifenjifen",is_time,"is_time");
})

function init()
{
	 $(".load-div").fadeOut();
	 $(".swiper-container").fadeIn();
	//alert("getUserData");
	 
}
function set_question(ques_arr){
	let arr = ques_arr;
	jifen_all = ques_arr.length
	return_obj = ques_arr[0];
	$("#timu_content").html('');
	arr.forEach(function(item,index){
	// console.log(item,index);
	// let new_str = ''
	let ques_txt = item.question;
	let ans_txt = item.answer;
	let correctan_swer = item.correctanswer;
	item.question = ques_txt.replace('\r\n', '<br>')
	item.answer = ans_txt.replace('\r\n', '<br>')
	item.correctanswer = correctan_swer.replace('\r\n', '<br>')
	let new_index = numberToChinese(index+1)
		let html = ''
		html += '<div class="swiper-slide t'+ (index+1) +'">';
		html += '<span class="title pos-ab">第'+ new_index +'题</span>';
		html += '<div class="timu_content_box pos-ab">';
		html += '<div class="question_text text_start">';
		html += '<img class="question_img" src="img/ques_img_icon.png?v=1.1">';
		html += '<span class="ques_text">'+ item.question +'</span>';
		html += '</div>';
		html += '<div class="text_content text_start">';
		html += '<img class="question_img" src="img/ans_img_icon.png?v=1.1">';
		html += '<span class="online_answer_text">'+ item.answer +'</span>';
		html += '</div>';
		html += '</div>';
		
		$("#timu_content").append(html)
	})
	
}

function get_timu(){
	$.ajax({
		url : 'http://wx.whyimingkeji.com/zcivcase/index.php?form-form_tiku',
		data: {a:1},
		dataType:'json',
		type:'post',
		success:function(res){
			 console.log(res)
				if(res.return_code == "success"){
					ques_arr = [];
					ques_arr = ques_arr.concat(res.return_data) ;
					console.log(ques_arr,"ques_arr");
					setData();
					setEvent();
			 }else{
				alert(res.return_msg)
			 }
		 }  
	});
}

function setData(){
	set_question(ques_arr); //加载slide
	mySwiper = new Swiper('.swiper-container', {
		spaceBetween: 0,
		noSwiping : true,
		// direction: 'vertical',
		direction: 'horizontal',
		observer:true,
		observeParents:true,
		autoHeight: true, 
		loop:false,
		on:{
			init: function(){
				swiperAnimateCache(this); //隐藏动画元素 
				swiperAnimate(this); //初始化完成开始动画
			}, 
			slideChangeTransitionStart: function(){
				// console.log("slideChangeTransitionStart:"+this.activeIndex);
			},
			slideChangeTransitionEnd: function(){ 
				swiperAnimate(this); //每个slide切换结束时也运行当前slide动画
				//this.slides.eq(this.activeIndex).find('.ani').removeClass('ani'); 动画只展现一次，去除ani类名
				console.log("slideChangeTransitionEnd:"+this.activeIndex);
				// console.log("slideChangeTransitionEnd:"+this.realIndex);
			},
		}
	});
	mySwiper2 = new Swiper ('.swiper2', {
		direction: 'horizontal', // 垂直切换选项
		loop: false, // 循环模式选项
		noSwiping : true,
		effect: 'fade',
		fadeEffect:{
			crossFade:true,
		},
		on:{
			init: function(){
				swiperAnimateCache(this); //隐藏动画元素 
				swiperAnimate(this); //初始化完成开始动画
			}, 
			slideChangeTransitionStart: function(){
				// console.log("slideChangeTransitionStart:"+this.activeIndex);
			},
			slideChangeTransitionEnd: function(){ 
				swiperAnimate(this); //每个slide切换结束时也运行当前slide动画
				//this.slides.eq(this.activeIndex).find('.ani').removeClass('ani'); 动画只展现一次，去除ani类名
				console.log("slideChangeTransitionEnd:"+this.activeIndex);
				curNum = this.realIndex + 1;
				return_obj = ques_arr[curNum-1]
				console.log(jifen,"jifenjifenjifen",curNum,'当前第几页',return_obj,'当前页面下的对象');
				// console.log("slideChangeTransitionEnd:"+this.realIndex);
				// if(this.activeIndex == 24){
				if (this.activeIndex === this.slides.length - 1) {
				        // 到达最后一页的逻辑处理
					console.log('到达了最后一页',is_time,"is_timeis_timeis_time");
					if(is_time == false){
						$('.answer_next_btn').text('提交查看成绩')
						$(".answer_next_btn").click(function(){
							$(".answer_box").hide()
								jiang_result()
						})
						// $(".succ_btn, .error_btn").click(function(){
						// 	jiang_result()
						// })
					}
					
				}
			},
		}
	}) 
}
function gotoPage(n){
	console.log(n)
	mySwiper.slideTo(n,200,true)
	
}
// 生成二维码的函数
function generateQRCode(id, text) {
	var qrCode = new QRCode(document.getElementById(id), {
		text: text,
		width: 128,
		height: 128,
		colorDark : "#000000",
		colorLight : "#ffffff",
		correctLevel : QRCode.CorrectLevel.H
	});
}

function updateCountdown(timer_num) {
    timeClock = setInterval(function(){
        timer_num--;
        $('.clock').html(timer_num);
        if (timer_num == 0) {
            clearInterval(timeClock);
            $('.clock').html(timer_num_all);
			if(is_time == false){
				jiang_result()
			}
        } 
    },1000)
}
 function jiang_result(){
	is_time = true
	fenshu_post(jifen)
 }

function sure_question(ans){
		if(ans == return_obj.correctoption){
			console.log('答案正确，弹窗出正确答案');
			jifen = jifen + 1;
			if(jifen > jifen_all){
				return false
			}
		}else{
			console.log('答案错误，弹窗出错误答案');
		}
		$(".answer_text").html(return_obj.correctanswer)
		$(".answer_box").show()
}

//数字转成中文
function numberToChinese(num) {
		const texts = { 0: '零', 1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六', 7: '七', 8: '八', 9: '九' }
		const units = ['十', '百', '千', '万']
		let res = ''
		if (num < 10) {
			res = texts[num] || ''
		} else {
			let numSources = (num + '').split('').reverse()
			let _length = numSources.length
			let numTexts = []
			for (let i = 0; i < _length; i++) {
				const cur = Number(numSources[i])
				// console.log('ask-cur', cur, i, _length)
				if (i >= 1 && cur !== 0) {
					numTexts.unshift(units[i - 1])
				}
				if (i === 0 && cur === 0) {
					continue
				}
				if (cur === 0 && Number(numSources[i - 1]) === 0) {
					continue
				}
				if (i === 1 && num < 20) {
					continue
				}
				numTexts.unshift(numberToChinese(cur))
				// console.log('ask-curNumTexts', numTexts.toString())
			}
			res = numTexts.join('')
		}
		// console.log(res,"2222");
		return res
}

 // 日期转大写
 function dateToChinese(date) {
	const chineseNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
	let year = date.getFullYear().toString();
	let month = (date.getMonth() + 1).toString();
	let day = date.getDate().toString();
	let chineseDate = year.replace(/\d/g, (match) => {
	return chineseNums[Number(match)];
	});
	chineseDate += '年';
	chineseDate += month.replace(/\d/g, (match) => {
	return chineseNums[Number(match)];
	});
	chineseDate += '月';
	chineseDate += day.replace(/\d/g, (match) => {
	return chineseNums[Number(match)];
	});
	chineseDate += '日';
	return chineseDate;
}

function fenshu_post(num){
	if(num == 0){
		num = 1
	}
	$.ajax({
		url : 'http://wx.whyimingkeji.com/zcivcase/index.php?form-form_dati',
		data: {num:num},
		dataType:'json',
		type:'post',
		success:function(res){
			 console.log(res)
			 if(res.return_code == "success"){
				is_token = res.return_data.suijishu
				let yuming_name = 'http://wx.whyimingkeji.com/wx/sihuo_fanshu/index_phone.html?v='+ timestamp + '&mid=' + is_token
				generateQRCode('qrcode', yuming_name);	
				if(num > 0 && num < 11){
					$(".jiang_img").attr("src","img/jiang3.png?v="+timestamp)
				}
				else if(num > 10 && num < 21){
					$(".jiang_img").attr("src","img/jiang2.png?v="+timestamp)
				}
				else if(num > 20 && num < 26){
					$(".jiang_img").attr("src","img/jiang1.png?v="+timestamp)
				}
				setTimeout(() => {
					$(".jiang_div").show()
				}, 500);
				
				
			 }else{
				alert(res.return_msg)
			 }
			 setTimeout(() => {
				window.location.reload();
				is_time = false;
			}, 30 * 1000);
		 }  
	});
}
let p2_id = 0;
var btn_onClick = false; //60s内没有点击按钮就刷新页面
var p2_time = 60; //页面60s内没有点击就刷新页面
var p2_timer 
function show_alert(id){
	console.log(id,"ididiididdi");
	p2_id = id
	$(".p2_answer_box").show()
	if(btn_onClick == false){
		
		p2_timer = setInterval(function(){
			p2_time--;
			if(p2_time == 0 ){
				clearInterval(p2_timer);
				window.location.reload(); //刷新页面
			}
		},1000);
	}
}

$(".submit_next_btn").click(function(){
	btn_onClick = true;
	clearInterval(p2_timer);
	let obj = {}
	if(p2_id == 1){
		p2_id = "教职工"
	}
	else if(p2_id == 2){
		p2_id = "学生"

	}else{
		p2_id = "来宾"
	}
	obj.p_id = p2_id;
	obj.area = $("#area_input").val()
	obj.work = $("#work_input").val()
	obj.name = $("#name_input").val()
	obj.school = $("#school_input").val()
	console.log(obj,"objobjobj");

	if(obj.area == "" && obj.work == "" && obj.name == "" && obj.school == ""){

	}else{
		//调接口

		$.ajax({
		url : 'https://wx.whyimingkeji.com/zcivcase/index.php?form-form_tiku2',
		data: {type:obj.p_id,name:obj.name,number:obj.work,college:obj.school,department:obj.area},
		dataType:'json',
		type:'post',
		success:function(res){
				console.log(res)
				// alert("报名成功")
			}  
		});
	}


	gotoPage(2)
	// 初始化倒计时
	updateCountdown(timer_num);
	
})



$(".p2_answer_box").click(function(e){
	e.stopPropagation();
	// $(".p2_answer_box").hide()
})
function setEvent(){
	
	// 绘制日期  获取当前日期
	const date = new Date();
	$(".time_txt").html(dateToChinese(date))
	$(".p1_btn").click(function(){
		console.log('点击')
		gotoPage(1)
	});





	// 默认第一题答案 先渲染第一题的答案 a和b ，对比返回的correctoption ，答完先出弹窗，显示答对或者答错，点击弹窗再到下一题 
$(".succ_btn,.error_btn, .c_btn, .d_btn").click(function(){
		let data_ = $(this).data('option');
		sure_question(data_)
})
$(".answer_next_btn").click(function(){
	$(".answer_box").hide()
		mySwiper2.slideNext();
})
	
	$(".back_btn").click(function(){
		gotoPage(0)
		clearInterval(timeClock);
        $('.clock').html(timer_num_all);
		is_time = false;
		jifen = 0;
	})
	$(".p3_back_btn").click(function(){
		// gotoPage(0)
		window.location.reload();
	})
	$('.p8_btn').click(function(){
		// 请求
		$.ajax({
		url : 'https://wx.whyimingkeji.com/zcivcase/index.php?form-form_20220519',
		data: {truename:truename,phone:moblie,renshu:renshu},
		dataType:'json',
		type:'post',
		success:function(res){
			 console.log(res)
			 alert("报名成功")
		 }  
		});
	})
}
	